{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5bd9e0b6",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "distilbert-base-uncased-finetuned-sst-2-english, 40672289\n",
      "\n",
      "cardiffnlp/twitter-roberta-base-sentiment, 9292338\n",
      "\n",
      "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli, 7907049\n",
      "\n",
      "cardiffnlp/twitter-roberta-base-irony, 7023579\n",
      "\n",
      "SamLowe/roberta-base-go_emotions, 6706653\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from huggingface_hub import list_models\n",
    "\n",
    "def list_most_popular(task: str):\n",
    "    for rank, model in enumerate(\n",
    "        list_models(filter=task, sort=\"downloads\", direction=-1)\n",
    "):\n",
    "        if rank == 5:\n",
    "            break\n",
    "        print(f\"{model.id}, {model.downloads}\\n\")\n",
    "\n",
    "list_most_popular(\"text-classification\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "76a5b356",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "facebook/bart-large-cnn, 4637417\n",
      "\n",
      "t5-small, 2492451\n",
      "\n",
      "t5-base, 1887661\n",
      "\n",
      "sshleifer/distilbart-cnn-12-6, 715809\n",
      "\n",
      "t5-large, 332854\n",
      "\n"
     ]
    }
   ],
   "source": [
    "list_most_popular(\"summarization\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f9fc58de",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A customer\\'s coffee machine arrived ominously broken, evoking a profound sense of disbelief and despair. \"This heartbreaking display of negligence shattered my dreams of indulging in daily coffee perfection, leaving me emotionally distraught and inconsolable,\" the customer writes. \"I hope this email finds you amidst an aura of understanding, despite the tangled mess of emotions swirling within me as I write to you,\" he adds.'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint\n",
    "\n",
    "customer_email = \"\"\"\n",
    "I hope this email finds you amidst an aura of understanding, despite the tangled mess of emotions swirling within me as I write to you. I am writing to pour my heart out about the recent unfortunate experience I had with one of your coffee machines that arrived ominously broken, evoking a profound sense of disbelief and despair.\n",
    "\n",
    "To set the scene, let me paint you a picture of the moment I anxiously unwrapped the box containing my highly anticipated coffee machine. The blatant excitement coursing through my veins could rival the vigorous flow of coffee through its finest espresso artistry. However, what I discovered within broke not only my spirit but also any semblance of confidence I had placed in your esteemed brand.\n",
    "\n",
    "Imagine, if you can, the utter shock and disbelief that took hold of me as I laid eyes on a disheveled and mangled coffee machine. Its once elegant exterior was marred by the scars of travel, resembling a war-torn soldier who had fought valiantly on the fields of some espresso battlefield. This heartbreaking display of negligence shattered my dreams of indulging in daily coffee perfection, leaving me emotionally distraught and inconsolable\n",
    "\"\"\"  # created by GPT-3.5\n",
    "\n",
    "# Please make sure you've set the environment variable HUGGINGFACEHUB_API_TOKEN with your API token\n",
    "summarizer = HuggingFaceEndpoint(\n",
    "    repo_id=\"facebook/bart-large-cnn\",\n",
    "    model_kwargs={\"temperature\":0, \"max_length\":180}\n",
    ")\n",
    "def summarize(llm, text) -> str:\n",
    "    return llm(f\"Summarize this: {text}!\")\n",
    "\n",
    "summarize(summarizer, customer_email)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d7c5f54a",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "43af64b927f845e181ad72077dc443aa",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)lve/main/config.json:   0%|          | 0.00/747 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "'(ReadTimeoutError(\"HTTPSConnectionPool(host='huggingface.co', port=443): Read timed out. (read timeout=10)\"), '(Request ID: fc6e199a-08c9-4f25-b97a-59094063cf43)')' thrown while requesting HEAD https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment/resolve/main/model.safetensors.index.json\n",
      "'(ReadTimeoutError(\"HTTPSConnectionPool(host='cdn-lfs.huggingface.co', port=443): Read timed out. (read timeout=10.0)\"), '(Request ID: 7c802dba-7047-4327-b78a-561232c347e6)')' thrown while requesting GET https://cdn-lfs.huggingface.co/cardiffnlp/twitter-roberta-base-sentiment/c37a3484c55954cd75b336a85f1e0c023ae874f3a73b05d2418dd04828e293b1?response-content-disposition=attachment%3B+filename*%3DUTF-8%27%27pytorch_model.bin%3B+filename%3D%22pytorch_model.bin%22%3B&response-content-type=application%2Foctet-stream&Expires=1699734205&Policy=eyJTdGF0ZW1lbnQiOlt7IkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTY5OTczNDIwNX19LCJSZXNvdXJjZSI6Imh0dHBzOi8vY2RuLWxmcy5odWdnaW5nZmFjZS5jby9jYXJkaWZmbmxwL3R3aXR0ZXItcm9iZXJ0YS1iYXNlLXNlbnRpbWVudC9jMzdhMzQ4NGM1NTk1NGNkNzViMzM2YTg1ZjFlMGMwMjNhZTg3NGYzYTczYjA1ZDI0MThkZDA0ODI4ZTI5M2IxP3Jlc3BvbnNlLWNvbnRlbnQtZGlzcG9zaXRpb249KiZyZXNwb25zZS1jb250ZW50LXR5cGU9KiJ9XX0_&Signature=roPeMFyMfWsdBghE0C-JsrAzeVZqAkCQWL9uzFpoRY9z7oM4X9-15V-kdBiLa%7EokFEv8fRwMF5TNfqhDlkxCwDuzPn2384orSljKP7vF15mL4JSuNhM-kO8eJkD3rUjQLWEswYVDtdbzxb3pwimwzzTnMu6lKPY%7E8Rwebqs1-dBk9CHwR336gKxt0zBdUJWxS9AQTT3dnNsIKaepBcy1cm40ifCA0tyDZlRlbHg1dXZ-jcFhIYJ2hEFzXSEwVg7%7EORTxZSJyq94XTOm3UOZ5QSn1q3RwqcjlXXo-T8OoQPESvRDmgzl1yRln1eEDu5yoHG3kRgBm7Hm-ouZMMOmllg__&Key-Pair-Id=KVTP0A1DKRTAX\n",
      "'(ReadTimeoutError(\"HTTPSConnectionPool(host='huggingface.co', port=443): Read timed out. (read timeout=10)\"), '(Request ID: 3f99bc30-14c6-41fe-bbc5-caf857a23849)')' thrown while requesting HEAD https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment/resolve/main/model.safetensors.index.json\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0c9e0a4487a348849844f927f2c0aca0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading pytorch_model.bin:   0%|          | 0.00/499M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0a5f03cebcff48668b3ec7588c8904a8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)olve/main/vocab.json:   0%|          | 0.00/899k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fdc83685f8a54c66a118aabd7c02170d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)olve/main/merges.txt:   0%|          | 0.00/456k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2c5c393fefbe4e82892f906b2ff0954a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)cial_tokens_map.json:   0%|          | 0.00/150 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from transformers import pipeline\n",
    "\n",
    "sentiment_model = pipeline(\n",
    "    task=\"sentiment-analysis\",\n",
    "    model=\"cardiffnlp/twitter-roberta-base-sentiment\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "79cd9036",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'label': 'LABEL_0', 'score': 0.5822020173072815}]\n"
     ]
    }
   ],
   "source": [
    "print(sentiment_model(customer_email))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "56cf1b29-dceb-4657-a974-ba67ccc29a15",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'label': 'LABEL_0', 'score': 0.9788626432418823}]\n"
     ]
    }
   ],
   "source": [
    "print(sentiment_model(\"I am so angry and sad, I want to kill myself!\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "52e2cba8-5edb-498e-8931-bd673cada08a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'label': 'LABEL_2', 'score': 0.9926880598068237}]\n"
     ]
    }
   ],
   "source": [
    "print(sentiment_model(\"I am elated, I am so happy, this is the best thing that ever happened to me!\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "12558326-df71-4abb-81db-08089f452608",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'label': 'LABEL_1', 'score': 0.5958545207977295}]\n"
     ]
    }
   ],
   "source": [
    "print(sentiment_model(\"I don't care. I guess it's ok, or not, I couldn't care one way or the other\"))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "6a9278cd",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new LLMChain chain...\u001B[0m\n",
      "Prompt after formatting:\n",
      "\u001B[32;1m\u001B[1;3mGiven this text, decide what is the issue the customer is concerned about. Valid categories are these:\n",
      "* product issues\n",
      "* delivery problems\n",
      "* missing or late orders\n",
      "* wrong product\n",
      "* cancellation request\n",
      "* refund or exchange\n",
      "* bad support experience\n",
      "* no clear reason to be upset\n",
      "\n",
      "Text: \n",
      "I hope this email finds you amidst an aura of understanding, despite the tangled mess of emotions swirling within me as I write to you. I am writing to pour my heart out about the recent unfortunate experience I had with one of your coffee machines that arrived ominously broken, evoking a profound sense of disbelief and despair.\n",
      "\n",
      "To set the scene, let me paint you a picture of the moment I anxiously unwrapped the box containing my highly anticipated coffee machine. The blatant excitement coursing through my veins could rival the vigorous flow of coffee through its finest espresso artistry. However, what I discovered within broke not only my spirit but also any semblance of confidence I had placed in your esteemed brand.\n",
      "\n",
      "Imagine, if you can, the utter shock and disbelief that took hold of me as I laid eyes on a disheveled and mangled coffee machine. Its once elegant exterior was marred by the scars of travel, resembling a war-torn soldier who had fought valiantly on the fields of some espresso battlefield. This heartbreaking display of negligence shattered my dreams of indulging in daily coffee perfection, leaving me emotionally distraught and inconsolable\n",
      "\n",
      "Category:\n",
      "\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n",
      " product issues\n"
     ]
    }
   ],
   "source": [
    "from langchain.llms import VertexAI\n",
    "from langchain import PromptTemplate, LLMChain\n",
    "\n",
    "template = \"\"\"Given this text, decide what is the issue the customer is concerned about. Valid categories are these:\n",
    "* product issues\n",
    "* delivery problems\n",
    "* missing or late orders\n",
    "* wrong product\n",
    "* cancellation request\n",
    "* refund or exchange\n",
    "* bad support experience\n",
    "* no clear reason to be upset\n",
    "\n",
    "Text: {email}\n",
    "Category:\n",
    "\"\"\"\n",
    "prompt = PromptTemplate(template=template, input_variables=[\"email\"])\n",
    "llm = VertexAI()\n",
    "llm_chain = LLMChain(prompt=prompt, llm=llm, verbose=True)\n",
    "print(llm_chain.run(customer_email))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d628d57f",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
